package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.enums.CommentType;
import com.tanhua.dubbo.enums.IdType;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.service.IdService;
import com.tanhua.dubbo.service.TimeLineService;
import com.tanhua.dubbo.vo.PageInfo;
import javafx.collections.transformation.SortedList;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.ArrayList;
import java.util.List;

@DubboService(version = "1.0.0")
public class QuanZiApiImpl implements QuanZiApi {

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private IdService idService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 查询好友动态
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        //查询好友的动态实际上就是查询自己的时间线表
        PageRequest pageRequest = PageRequest.of(page - 1,
                pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageRequest);
        List<TimeLine> timeLineList = this.mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);

        //获取发布id列表
        List<Object> publishIdList = CollUtil.getFieldValues(timeLineList, "publishId");

        //构造查询动态的条件
        Query queryPublish = Query.query(Criteria.where("id").in(publishIdList))
                .with(Sort.by(Sort.Order.desc("created")));

        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);

        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);
        pageInfo.setRecords(publishList);

        return pageInfo;
    }

    /**
     * 发布动态
     *
     * @param publish
     * @return 发布成功返回动态id
     */
    @Override
    public String savePublish(Publish publish) {
        //基础的校验
        if (!ObjectUtil.isAllNotEmpty(publish.getUserId(), publish.getText(), publish.getMedias())) {
            return null;
        }

        //设置基础数据
        publish.setId(ObjectId.get());//主键
        publish.setSeeType(1);
        publish.setCreated(System.currentTimeMillis());
        publish.setPid(this.idService.createId(IdType.PUBLISH)); //自增长id

        //写入到发布表
        this.mongoTemplate.save(publish);

        //写入到自己的相册表
        Album album = new Album();
        album.setId(ObjectId.get());
        album.setPublishId(publish.getId());
        album.setCreated(System.currentTimeMillis());
        this.mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

        //异步写入到好友的时间线表
        this.timeLineService.saveTimeLine(publish);

        //TODO 事务问题
        //解决：开启事务的注解，MongoDB是支持事务的，但是单节点的MongoDB是不支持的，只有在集群下支持
        //思考：这里真的需要事务吗？ 一旦开始了事务，就意味着这里的业务是强一致性
        //结合业务，对于写入相册表或写入时间线表失败的情况，应该采用补偿机制完成
        //具体方式：如果出错，记录日志，后台专用的程序进行日志的处理，这种方式交弱一致性
        //建议：在项目实战中完成

        return publish.getId().toString();
    }

    /**
     * 查询推荐动态
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page,
                                                       Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        String redisKey = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String redisValue = this.redisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isEmpty(redisValue)) {
            //没有推荐数据
            return pageInfo;
        }

        //长度是20
        List<String> pidStrList = StrUtil.split(redisValue, ',');

        //计算分页的下标
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);//[0, 10]
        int startIndex = startEnd[0];
        int endIndex = Math.min(startEnd[1], pidStrList.size());

        //真正需要的pid列表
        List<Long> pidList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidList.add(Convert.toLong(pidStrList.get(i)));
        }

        if (CollUtil.isEmpty(pidList)) {
            //没有推荐数据
            return pageInfo;
        }

        pageInfo.setRecords(new ArrayList<>());

        //MongoDB中查询Publish数据
        Query query = Query.query(Criteria.where("pid").in(pidList));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);

        //按照推荐的顺序返回数据
        for (Long pid : pidList) {
            for (Publish publish : publishList) {
                if (ObjectUtil.equal(pid, publish.getPid())) {
                    pageInfo.getRecords().add(publish);
                    break;
                }
            }
        }

        return pageInfo;
    }

    /**
     * 根据id查询动态
     *
     * @param id 动态id
     * @return
     */
    @Override
    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    /**
     * 点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //判断用户是否已经点赞，如果已经点赞就返回
        if (this.queryUserIsLike(userId, publishId)) {
            return false;
        }

        //保存点赞记录到MongoDB
        Comment comment = new Comment();
        comment.setId(ObjectId.get());
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setPublishId(new ObjectId(publishId));
        comment.setUserId(userId);

        //查询发布对象，获取发布动态的人
        Publish publish = this.queryPublishById(publishId);
        comment.setPublishUserId(publish.getUserId());
        comment.setIsParent(false);
        comment.setCreated(System.currentTimeMillis());
        this.mongoTemplate.save(comment);

        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LIKE.name();
        //点赞数+1
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
        //标识某一个用户对该动态是否点赞
        this.redisTemplate.opsForHash().put(redisKey, getCommentUserLikeRedisKey(userId), "1");
        return true;
    }

    private String getCommentRedisKey(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKey(Long userId) {
        return COMMENT_USER_LIKE_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 取消点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        //判断用户是否已经点赞，如果没有点赞就返回
        if (!this.queryUserIsLike(userId, publishId)) {
            return false;
        }

        //删除MongoDB中的数据记录
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.LIKE.getType()));
        this.mongoTemplate.remove(query, Comment.class);

        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LIKE.name();
        //点赞数-1
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);
        //删除该用户对该动态是否点赞的标识
        this.redisTemplate.opsForHash().delete(redisKey, getCommentUserLikeRedisKey(userId));
        return true;
    }

    /**
     * 查询点赞数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryLikeCount(String publishId) {
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LIKE.name();
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        return Convert.toLong(value, 0L);
    }

    /**
     * 查询用户是否点赞该动态
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = this.getCommentUserLikeRedisKey(userId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    /**
     * 查询相册表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //查询自己的相册表
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        List<Album> albumList = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        if (CollUtil.isEmpty(albumList)) {
            return pageInfo;
        }

        //查询发布动态的数据
        Query queryPublish = Query.query(Criteria.where("id")
                .in(CollUtil.getFieldValues(albumList, "publishId")))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);
        pageInfo.setRecords(publishList);

        return pageInfo;
    }


    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }
    /**
     * 喜欢
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean loveComment(Long userId, String publishId) {
        //判断用户是否已经喜欢
        if(this.queryUserIsLove(userId,publishId)){
            return false;
        }

        //保存点赞记录到MongoDB
        Comment comment = new Comment();
        comment.setId(ObjectId.get());
        comment.setPublishId(new ObjectId(publishId));
        comment.setUserId(userId);
        comment.setCommentType(CommentType.LOVE.getType());

        //查询发布对象，获取发布动态的人
        Publish publish = this.queryPublishById(publishId);
        comment.setPublishUserId(publish.getUserId());
        comment.setIsParent(false);
        comment.setCreated(System.currentTimeMillis());
        this.mongoTemplate.save(comment);

        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LOVE.name();
        //喜欢数+1
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
        //标识某一个用户对该动态是否点赞
        this.redisTemplate.opsForHash().put(redisKey, getCommentUserLoveRedisKey(userId), "1");
        return true;
    }

    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        //判断用户是否已喜欢该动态
        if (!this.queryUserIsLike(userId,publishId)){
            return false;
        }
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.LOVE.getType()));
        this.mongoTemplate.remove(query, Comment.class);
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LOVE.name();
        //喜欢数-1
        this.redisTemplate.opsForHash().increment(redisKey,hashKey,-1);
        //删除该用户对该动态是否点赞的标识
        this.redisTemplate.opsForHash().delete(redisKey,this.getCommentUserLoveRedisKey(userId));
        return true;
    }

    @Override
    public Long queryLoveCount(String publishId) {
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LOVE.name();
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        return Convert.toLong(value,0L);
    }

    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    /**
     * 查询评论列表
     * @param publishId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {

        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        //分页查询
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("created")));
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(CommentType.COMMENT.getType())).with(pageRequest);

        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);
        pageInfo.setRecords(commentList);
        return pageInfo;
    }

    /**
     * 发表评论
     * @param userId
     * @param publishId
     * @param content
     * @return
     */
    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        Comment comment = new Comment();
        comment.setId(ObjectId.get());
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(publishId));
        comment.setIsParent(false);
        comment.setCommentType(CommentType.COMMENT.getType());
        comment.setCreated(System.currentTimeMillis());
        Publish publish = this.queryPublishById(publishId);
        comment.setPublishUserId(publish.getUserId());
        comment.setContent(content);
        //保存到mongoDB
        this.mongoTemplate.save(comment);
        return true;
    }

    @Override
    public Long queryCommentCount(String publishId) {

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(CommentType.COMMENT.getType()));

        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);
        return Convert.toLong(CollUtil.count(commentList, null));
        /*for (int i = 0; i < commentList.size(); i++) {
             = array[i];
            */
        //return this.mongoTemplate.count(query,Publish.class);
    }

    @Override
    public double distance(Double longitude, Double latitude,String publishId,Long userId) {
        //查询条件
        //Query.query(Criteria.where())
        Object myLocation = this.mongoTemplate.find(null,UserLocation.class);
        NearQuery nearQuery = NearQuery.near(new GeoJsonPoint(longitude, latitude), Metrics.KILOMETERS);

        GeoResults<UserLocation> geoResults = this.mongoTemplate.geoNear(nearQuery, UserLocation.class);
        return 0;
    }

    @Override
    public List<Publish> queryAllPulish() {
        return this.mongoTemplate.findAll(Publish.class);
    }

}
